import axios from "axios"
import { mqttConfig, appBaseURKConfig, params, windowsData } from "../config/index.js"
const { mode } = params
console.log("request====>", mode)
console.log("windowsData.adsApiUrl===>", windowsData.adsApiUrl)
// 添加重试函数
async function retryRequest(requestFn, maxRetries = 3, delay = 1000) {
  let lastError
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await requestFn()
    } catch (error) {
      lastError = error
      console.error(`请求失败 (尝试 ${i + 1}/${maxRetries}):`, error.message)

      // 检查是否是EPIPE错误
      if (error.code === "EPIPE" || error.message.includes("EPIPE")) {
        console.error("检测到EPIPE错误，可能是AdsPower服务连接问题")
      }

      if (i < maxRetries - 1) {
        console.log(`等待 ${delay}ms 后重试...`)
        await new Promise((resolve) => setTimeout(resolve, delay))
      }
    }
  }
  throw lastError
}

// ads 实例
const instance1 = axios.create({
  baseURL: windowsData.adsApiUrl,
  timeout: 60 * 1000 * 10,
  headers: {
    "Content-Type": "application/json",
    "X-ScriptApp": "browser",
  },
})

// 后台 实例
const instance2 = axios.create({
  baseURL: appBaseURKConfig[mode],
  timeout: 60 * 1000 * 10,
  headers: {
    "X-ScriptApp": "browser",
  },
})

// 添加拦截器到两个实例
const addInterceptors = (instance) => {
  instance.interceptors.request.use(
    (config) => {
      console.log(`发送请求: ${config.method.toUpperCase()} ${config.url}`, config.data || config.params)
      return config
    },
    (error) => {
      console.error("请求错误:", error)
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (response) => {
      console.log(`收到响应: ${response.config.method.toUpperCase()} ${response.config.url}`, response.status, response.statusText)
      return response
    },
    (error) => {
      if (error.response) {
        // 服务器返回了错误状态码
        console.error(`响应错误: ${error.config.method.toUpperCase()} ${error.config.url}`, error.response.status, error.response.statusText)
        console.error("错误详情:", error.response.data)
      } else if (error.request) {
        // 请求已发送但没有收到响应
        console.error(`无响应: ${error.config.method.toUpperCase()} ${error.config.url}`, error.message)
      } else {
        // 请求设置时出错
        console.error("请求错误:", error.message)
      }
      return Promise.reject(error)
    }
  )
}

// 添加拦截器
addInterceptors(instance1)
addInterceptors(instance2)

// 创建API客户端
const createApiClient = (instance) => ({
  async get(url, config = {}) {
    return retryRequest(async () => {
      console.log(`GET请求: ${url}`, config)
      const response = await instance.get(url, config)
      console.log("get response.headers:x-trace-id", response.headers["x-trace-id"], url)
      return response.data
    })
  },

  async post(url, data, config = {}) {
    return retryRequest(async () => {
      console.log(`POST请求: ${url}`, data, config)
      const headers = config.headers || {}
      console.log("post----data===>", data)
      const response = await instance.post(url, data, {
        ...config,
        headers,
      })
      console.log("post response.headers:x-trace-id", response.headers["x-trace-id"], url)
      return response.data
    })
  },

  async put(url, data, config = {}) {
    return retryRequest(async () => {
      console.log(`PUT请求: ${url}`, data, config)

      const headers = config.headers || {}
      const response = await instance.put(url, data, {
        ...config,
        headers,
      })
      console.log("put response.headers:x-trace-id", response.headers["x-trace-id"], url)
      return response.data
    })
  },

  async delete(url, config = {}) {
    return retryRequest(async () => {
      console.log(`DELETE请求: ${url}`, config)
      const response = await instance.delete(url, config)
      console.log("delete response.headers:x-trace-id", response.headers["x-trace-id"], url)
      return response.data
    })
  },
})

// 导出API客户端
export const apiClient1 = createApiClient(instance1)
export const apiClient2 = createApiClient(instance2)
